package com.farm.portal.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.farm.core.sql.query.DBRule;
import com.farm.portal.domain.Component;
import com.farm.portal.domain.Componentdef;
import com.farm.portal.domain.Componentexcute;
import com.farm.portal.domain.Portal;
import com.farm.portal.domain.Portalexcute;
import com.farm.portal.domain.Portaltree;
import com.farm.core.auth.domain.LoginUser;
import com.farm.core.time.TimeTool;


import com.farm.portal.dao.ComponentDaoInter;
import com.farm.portal.dao.ComponentdefDaoInter;
import com.farm.portal.dao.ComponentexcuteDaoInter;
import com.farm.portal.dao.PortalDaoInter;
import com.farm.portal.dao.PortalexcuteDaoInter;
import com.farm.portal.dao.PortaltreeDaoInter;
import com.farm.portal.service.PortalServiceInter;
import com.farm.core.sql.query.DataQuery;

/* *
 *功能：门户配置服务实现类
 *详细：
 *
 *版本：v0.1
 *作者：王东
 *日期：20141122211253
 *说明：
 */
public class PortalServiceImpl implements PortalServiceInter {
	private PortaltreeDaoInter portaltreeDao;
	private ComponentdefDaoInter componentdefDao;
	private PortalDaoInter portalDao;
	private PortalexcuteDaoInter portalexcuteDao;
	private ComponentexcuteDaoInter componentexcuteDao;
	private ComponentDaoInter componentDao;
//	private static final Logger log = Logger.getLogger(PortalServiceImpl.class);

	private Portaltree insertPortaltreeEntity(Portaltree entity, LoginUser user) {
		entity.setCuser(user.getId());
		entity.setCtime(TimeTool.getTimeDate14());
		entity.setCusername(user.getName());
		entity.setEuser(user.getId());
		entity.setEusername(user.getName());
		entity.setEtime(TimeTool.getTimeDate14());
		entity.setPstate("1");
		if (entity.getParentid() == null) {
			entity.setParentid("NONE");
		}
		entity.setTreecode("NONE");
		entity = portaltreeDao.insertEntity(entity);
		if (entity.getParentid().equals("NONE")) {
			entity.setTreecode(entity.getId());
		} else {
			entity.setTreecode(portaltreeDao.getEntity(entity.getParentid())
					.getTreecode()
					+ entity.getId());
		}
		portaltreeDao.editEntity(entity);
		return entity;
	}


	private Portaltree getPortaltreeEntity(String id) {
		if (id == null) {
			return null;
		}
		return portaltreeDao.getEntity(id);
	}

	@Override
	public DataQuery createPortaltreeSimpleQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery
				.init(
						query,
						"FARM_PORTAL_TREE",
						"ID,COMPONENTDEFID,PORTALDEFID,CUSERNAME,CUSER,EUSERNAME,EUSER,PSTATE,PCONTENT,SORT,TYPE,TREECODE,PARENTID,NAME,ETIME,CTIME");
		return dbQuery;
	}

	@Override
	public Portaltree insertCategory(String name, int sort,
			LoginUser currentUser) {
		Portaltree entity = new Portaltree();
		entity.setName(name);
		entity.setSort(sort);
		entity.setType(NODE_TYPE.CATEGORY.getVal());
		insertPortaltreeEntity(entity, currentUser);
		return entity;
	}

	@Override
	public Portaltree insertPortal(String name, int sort, String keyStr,
			String categoryId, int colnum, String colwidth,
			LoginUser currentUser) {
		// 处理配置节点
		Portaltree entity = new Portaltree();
		entity.setName(name);
		entity.setSort(sort);
		entity.setType(NODE_TYPE.PORTAL.getVal());
		entity.setParentid(categoryId);
		entity = insertPortaltreeEntity(entity, currentUser);
		// 处理门户定义
		Portal portal = new Portal();
		portal.setColnum(colnum);
		portal.setKeystr(keyStr);
		portal.setColwidth(colwidth);
		portal.setCtime(TimeTool.getTimeDate14());
		portal.setCuser(currentUser.getId());
		portal.setCusername(currentUser.getName());
		portal.setEtime(TimeTool.getTimeDate14());
		portal.setEuser(currentUser.getId());
		portal.setEusername(currentUser.getName());
		portal.setPstate("1");
		portal = portalDao.insertEntity(portal);
		// 关联门户定义和配置节点
		entity.setPortaldefid(portal.getId());
		portaltreeDao.editEntity(entity);
		if (colwidth.split(",").length != colnum) {
			throw new RuntimeException("列数或列宽度录入有误！");
		}
		return entity;
	}

	@Override
	public Portaltree insertComponent(String name, int sort, String portalId,
			String componentid, String openable, String closable,
			String collapsible, int width, int heitgh, LoginUser currentUser) {
		// 处理配置节点
		Portaltree entity = new Portaltree();
		entity.setName(name);
		entity.setSort(sort);
		entity.setType(NODE_TYPE.COMPONENT.getVal());
		entity.setParentid(portalId);
		entity = insertPortaltreeEntity(entity, currentUser);
		// 处理组件定义
		Componentdef componentdef = new Componentdef();
		componentdef.setClosable(closable);
		componentdef.setCollapsible(collapsible);
		componentdef.setComponentid(componentid);
		componentdef.setCtime(TimeTool.getTimeDate14());
		componentdef.setCuser(currentUser.getId());
		componentdef.setCusername(currentUser.getName());
		componentdef.setEtime(TimeTool.getTimeDate14());
		componentdef.setEuser(currentUser.getId());
		componentdef.setEusername(currentUser.getName());
		componentdef.setHeitgh(heitgh);
		componentdef.setOpenable(openable);
		componentdef.setPstate("1");
		componentdef.setWidth(width);
		componentdef = componentdefDao.insertEntity(componentdef);
		// 关联门户定义和配置节点
		entity.setComponentdefid(componentdef.getId());
		portaltreeDao.editEntity(entity);
		return entity;
	}

	@Override
	public Portaltree editCategory(String treeNodeId, String name, int sort,
			LoginUser currentUser) {
		Portaltree entity2 = portaltreeDao.getEntity(treeNodeId);
		entity2.setEuser(currentUser.getId());
		entity2.setEusername(currentUser.getName());
		entity2.setEtime(TimeTool.getTimeDate14());
		entity2.setSort(sort);
		entity2.setName(name);
		portaltreeDao.editEntity(entity2);
		return entity2;
	}

	@Override
	public Portaltree editComponent(String treeNodeId, String name, int sort,
			String categoryid, String componentid, String openable,
			String closable, String collapsible, int width, int heitgh,
			LoginUser currentUser) {
		// 修改配置节点
		Portaltree entity2 = portaltreeDao.getEntity(treeNodeId);
		entity2.setEuser(currentUser.getId());
		entity2.setEusername(currentUser.getName());
		entity2.setEtime(TimeTool.getTimeDate14());
		entity2.setSort(sort);
		entity2.setName(name);
		portaltreeDao.editEntity(entity2);
		// 修改组件
		Componentdef componentdef = componentdefDao.getEntity(entity2
				.getComponentdefid());
		componentdef.setClosable(closable);
		componentdef.setCollapsible(collapsible);
		componentdef.setComponentid(componentid);
		componentdef.setEtime(TimeTool.getTimeDate14());
		componentdef.setEuser(currentUser.getId());
		componentdef.setEusername(currentUser.getName());
		componentdef.setHeitgh(heitgh);
		componentdef.setOpenable(openable);
		componentdef.setPstate("1");
		componentdef.setWidth(width);
		componentdefDao.editEntity(componentdef);
		return entity2;
	}

	@Override
	public Portaltree editPortal(String treeNodeId, String name, int sort,
			String keyStr, int colnum, String colwidth, LoginUser currentUser) {
		// 修改配置节点
		Portaltree entity2 = portaltreeDao.getEntity(treeNodeId);
		entity2.setEuser(currentUser.getId());
		entity2.setEusername(currentUser.getName());
		entity2.setEtime(TimeTool.getTimeDate14());
		entity2.setSort(sort);
		entity2.setName(name);
		portaltreeDao.editEntity(entity2);
		// 修改门户
		Portal portal = portalDao.getEntity(entity2.getPortaldefid());
		portal.setColnum(colnum);
		portal.setKeystr(keyStr);
		portal.setColwidth(colwidth);
		portal.setCtime(TimeTool.getTimeDate14());
		portal.setCuser(currentUser.getId());
		portal.setCusername(currentUser.getName());
		portal.setEtime(TimeTool.getTimeDate14());
		portal.setEuser(currentUser.getId());
		portal.setEusername(currentUser.getName());
		portal.setPstate("1");
		portalDao.editEntity(portal);
		return entity2;
	}

	@Override
	public void deleteTreeNode(String treeNodeId, LoginUser currentUser) {
		Portaltree node = getTreeNode(treeNodeId);
		// 删除分类
		if (node.getType().equals(NODE_TYPE.CATEGORY.getVal())) {
			// 门户集合
			List<Portaltree> nodes = portaltreeDao.selectEntitys(DBRule
					.addRule(new ArrayList<DBRule>(), "PARENTID", treeNodeId,
							"="));
			// 删除门户
			for (Portaltree porNode : nodes) {
				deletePortal(porNode.getId(), currentUser);
			}
			// 删除分类
			portaltreeDao.deleteEntity(node);
		}
		// 删除门户
		if (node.getType().equals(NODE_TYPE.PORTAL.getVal())) {
			deletePortal(treeNodeId, currentUser);
		}
		// 删除组件
		if (node.getType().equals(NODE_TYPE.COMPONENT.getVal())) {
			deleteComponent(treeNodeId, currentUser);
		}

	}

	/**
	 * 删除门户定义
	 * 
	 * @param treeNodeId
	 * @param currentUser
	 */
	private void deletePortal(String treeNodeId, LoginUser currentUser) {
		Portaltree node = getTreeNode(treeNodeId);
		String portalId = node.getPortaldefid();
		// 组价集合
		List<Portaltree> nodes = portaltreeDao.selectEntitys(DBRule.addRule(
				new ArrayList<DBRule>(), "PARENTID", treeNodeId, "="));
		// 删除组件
		for (Portaltree comnode : nodes) {
			deleteComponent(comnode.getId(), currentUser);
		}
		// 删除门户实例
		portalexcuteDao.deleteEntitys(DBRule.addRule(new ArrayList<DBRule>(),
				"PORTALDEFID", portalId, "="));
		// 删除门户分类
		portaltreeDao.deleteEntity(node);
		// 删除门户定义
		portalDao.deleteEntity(portalDao.getEntity(node.getPortaldefid()));
	}

	/**
	 * 删除组件定义
	 * 
	 * @param treeNodeId
	 * @param currentUser
	 */
	private void deleteComponent(String treeNodeId, LoginUser currentUser) {
		Portaltree node = getTreeNode(treeNodeId);
		String componentdefid = node.getComponentdefid();
		Componentdef componentDef = componentdefDao.getEntity(componentdefid);
		// 删除组件实例
		componentexcuteDao
				.deleteEntitys(DBRule.addRule(new ArrayList<DBRule>(),
						"COMPONENTDEFID", componentdefid, "="));
		// 删除组件分类
		portaltreeDao.deleteEntity(node);
		// 删除组件定义
		componentdefDao.deleteEntity(componentDef);
	}

	@Override
	public Componentdef getComponentDef(String componentdefid) {
		return componentdefDao.getEntity(componentdefid);
	}

	@Override
	public Portal getPortalDef(String portaldefid) {
		return portalDao.getEntity(portaldefid);
	}

	@Override
	public Portaltree getTreeNode(String treeNodeId) {
		return this.getPortaltreeEntity(treeNodeId);
	}

	// ----------------------------------------------------------------------------------
	public PortaltreeDaoInter getPortaltreeDao() {
		return portaltreeDao;
	}

	public PortalexcuteDaoInter getPortalexcuteDao() {
		return portalexcuteDao;
	}

	public void setPortalexcuteDao(PortalexcuteDaoInter portalexcuteDao) {
		this.portalexcuteDao = portalexcuteDao;
	}

	public ComponentexcuteDaoInter getComponentexcuteDao() {
		return componentexcuteDao;
	}

	public void setComponentexcuteDao(ComponentexcuteDaoInter componentexcuteDao) {
		this.componentexcuteDao = componentexcuteDao;
	}

	public void setPortaltreeDao(PortaltreeDaoInter dao) {
		this.portaltreeDao = dao;
	}

	public ComponentdefDaoInter getComponentdefDao() {
		return componentdefDao;
	}

	public ComponentDaoInter getComponentDao() {
		return componentDao;
	}

	public void setComponentDao(ComponentDaoInter componentDao) {
		this.componentDao = componentDao;
	}

	public void setComponentdefDao(ComponentdefDaoInter componentdefDao) {
		this.componentdefDao = componentdefDao;
	}

	public PortalDaoInter getPortalDao() {
		return portalDao;
	}

	public void setPortalDao(PortalDaoInter portalDao) {
		this.portalDao = portalDao;
	}

	@Override
	public Portal getUserPortal(String key, LoginUser currentUser) {
		Portal portal = portalDao.getEntityByKey(key);
		portal.setNode(portaltreeDao.getEntityByPortalId(portal.getId()));
		portal.setWidths(Arrays.asList(portal.getColwidth()
				.replaceAll("，", ",").split(",")));
		portal.setComponentdefs(portalDao.getUserPortalComponentDefs(key,currentUser.getId()));
		return portal;
	}

	@Override
	public Componentdef closeUserComponent(String portalKEY,
			String componentDefId, LoginUser currentUser) {

		return editUserComponent(portalKEY, componentDefId, currentUser, "1",
				null, null);
	}

	/**修改用户组件实例
	 * @param portalKEY
	 * @param componentDefId
	 * @param currentUser
	 * @param closeIs
	 *            是否关闭 （可为空，默认）
	 * @param collapsisIs
	 *            是否折叠（可为空，默认）
	 * @param sort
	 *            排序（可为空，默认）
	 * @return
	 */
	private Componentdef editUserComponent(String portalKEY,
			String componentDefId, LoginUser currentUser, String closeIs,
			String collapsisIs, Integer sort) {
		Portaltree node = portaltreeDao
				.getEntityByComponentDefId(componentDefId);
		Componentdef componentdef = componentdefDao.getEntity(componentDefId);
		Portal portal = portalDao.getEntityByKey(portalKEY);
		Portalexcute portalExcute = portalexcuteDao.getPortalExcuteOrInit(
				portal.getId(), currentUser.getId(), currentUser.getName());
		Componentexcute componentexcute = componentexcuteDao
				.getPortalExcuteOrInit(portal.getId(), componentdef.getId(),
						portalExcute.getId(), currentUser.getId(), currentUser
								.getName());
		// 保存用户组件配置
		if (closeIs != null) {
			componentexcute.setCloseis(closeIs);
		}
		if (collapsisIs != null) {
			componentexcute.setCollapsis(collapsisIs);
		}
		if (sort == null) {
			if (componentexcute.getSort() == 0) {
				componentexcute.setSort(node.getSort());
			}
		} else {
			componentexcute.setSort(sort);
		}
		componentexcute.setComponentdefid(componentDefId);
		componentexcute.setPortaldefid(portal.getId());
		componentexcute.setPortalexcuteid(portalExcute.getId());
		componentexcuteDao.editEntity(componentexcute);
		// 构造组件定义
		Component component = componentDao.getEntity(componentdef
				.getComponentid());
		componentdef.setNode(node);
		componentdef.setComponent(component);
		return componentdef;
	}

	@Override
	public Componentdef openUserComponent(String portalKEY,
			String componentDefId, LoginUser currentUser) {
		return editUserComponent(portalKEY, componentDefId, currentUser, "0",
				null, null);
	}

}
